<!DOCTYPE html>
<html lang="zh-CN">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="utf-8">
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  
  
  <!-- 关键字 keywords -->
  
  <meta name="keywords" content="a,天赐,天赐の小站,博客">
  
  
  <title itemprop="name">JUC学习笔记-基础并发工具：Atomic包与CAS | 天赐の小站</title>
  
    <link rel="shortcut icon" href="//fastly.jsdelivr.net/gh/tiancixiong/cdn@v1.0/img/custom/favicon.ico">
  
  <meta http-equiv="x-dns-prefetch-control" content="on">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Noto+SerifMerriweather|Merriweather+Sans|Source+Code+Pro|Ubuntu:400,700|Noto+Serif+SC" media="all">
  <link rel="dns-prefetch" href="//cdn.jsdelivr.net">
  <link rel="stylesheet" id="saukra_css-css" href="https://cdn.jsdelivr.net/gh/tiancixiong/cdn@sakura-theme/css/style.css" type="text/css" media="all">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/tiancixiong/cdn@sakura-theme/css/lib.min.css" media="all">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/tiancixiong/cdn@sakura-theme/css/font.css" media="all">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/tiancixiong/cdn@sakura-theme/css/insight.css" media="all">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/tiancixiong/cdn@sakura-theme/css/jquery.fancybox.min.css" media="all">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/tiancixiong/cdn@sakura-theme/css/zoom.css" media="all">
  <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/tiancixiong/cdn@sakura-theme/css/sharejs.css">
<!--   <link rel="stylesheet" id="saukra_css-css" href="https://2heng.xin/wp-content/cache/autoptimize/css/autoptimize_ad42a61f4c7d4bdd9f91afcff6b5dda5.css
" type="text/css" media="all"> -->
  <script>
  /*Initial Variables*/
  var mashiro_option = new Object();
  var mashiro_global = new Object();
  mashiro_option.NProgressON = true;
  /* 
   * 邮箱信息之类的东西可以填在这里，这些js变量基本都作用于sakura-app.js
   * 这样的设置仅是为了方便在基于PHP开发的主题中设置js变量，既然移植到了Node上，我想或许可以精简这一逻辑吧
   */
  mashiro_option.email_domain = "";
  mashiro_option.email_name = "";
  mashiro_option.cookie_version_control = "";
  mashiro_option.qzone_autocomplete = false;
  mashiro_option.site_name = "天赐の小站";
  mashiro_option.author_name = "天赐の小站";
  mashiro_option.site_url = "/";
  mashiro_option.v_appId = "VeenC2gYYyfSOq2rcCSmmruy-MdYXbMMI";
  mashiro_option.v_appKey = "F5kjyHdh4akqc7SDmfzQP8Qi";
  mashiro_option.v_notify = false;
  mashiro_option.v_verify = false;
  mashiro_option.v_placeholder = "你是我一生只会遇见一次的惊喜 ...";
  mashiro_option.v_avatar = "monsterid";
  mashiro_option.v_pageSize = "5" || 10;
  mashiro_option.mathjax = "0";
  mashiro_option.qq_api_url = "https://api.mashiro.top/qqinfo/"; 
  mashiro_option.qq_avatar_api_url = "https://api.mashiro.top/qqinfo/";

  // mashiro_option.jsdelivr_css_src = "https://cdn.jsdelivr.net/gh/moezx/cdn@3.4.5/css/lib.min.css";
  // mashiro_option.float_player_on = true;
  console.info("%c Blog %c", "background:#24272A; color:#ffffff", "", "https://blog.xiongtianci.com");
  console.info("%c GitHub %c", "background:#24272A; color:#ffffff", "", "https://github.com/tiancixiong");
  /*End of Initial Variables*/
  </script>
  <script type="text/javascript">
  var bg = "https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/5cm_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/5cm_03.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/A.Voyage.of.Chihiro_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/A.Voyage.of.Chihiro_02.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/A.Voyage.of.Chihiro_03.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/A.Voyage.of.Chihiro_04.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/A.Voyage.of.Chihiro_05.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/A.Voyage.of.Chihiro_06.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/A.Voyage.of.Chihiro_07.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/A.Voyage.of.Chihiro_08.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/A.Voyage.of.Chihiro_09.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/A.Voyage.of.Chihiro_10.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/A.Voyage.of.Chihiro_11.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/A.Voyage.of.Chihiro_12.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Atonement_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Atonement_02.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Atonement_03.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Atonement_04.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Avatar_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Before.Sunrise_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Before.Sunrise_02.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Before.Sunset_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/bighero_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/bighero_02.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/bighero_03.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Coco_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Coco_02.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Coco_03.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/CUG.King.of.Heroes_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Digimon_02.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Digimon_03.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Digimon_04.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Digimon_05.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Digimon_06.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Digimon_07.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Digimon_08.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Digimon_09.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Friends_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Friends_02.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Friends_03.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Friends_04.webp,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Friends_05.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Harry.Potter_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Harry.Potter_02.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Harry.Potter_03.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Harry.Potter_04.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Harry.Potter_05.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Hauru.no.ugoku.shiro_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Into.the.Wild_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Kaze.tachinu_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/kiki_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/kiki_03.png,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/kiki_04.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/kiminona_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/kiminona_02.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/kiminona_03.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/kiminona_06.png,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/kiminona_07.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/koenokatachi_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/koenokatachi_02.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/koenokatachi_03.png,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Kotonoha.no.Niwa_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/La.La.Land_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Le.Petit.Prince_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Le.Petit.Prince_02.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Mimi.wo.sumaseba_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Mr.Bean.Holiday_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Mr.Bean.Holiday_02.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Mr.Bean.Holiday_03.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Mr.Bean.Holiday_04.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Mr.Bean.Holiday_05.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/My.Sassy.Girl_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Paperman_01.png,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Paperman_02.png,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Piper_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Ponyo_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Ponyo_02.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Ponyo_03.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Reply.1988_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Reply.1988_02.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Reply.1988_03.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/SpiderMan.Into.the.SpiderVerse_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/SpiderMan.Into.the.SpiderVerse_02.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/SpiderMan.Into.the.SpiderVerse_03.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/The.Girl.Who.Leapt.Through.Time_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/The.Pianist_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/TheLonelyAndGreatGod_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Titanic_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Titanic_02.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Titanic_03.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/totoro1.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/WALL_E_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/WALL_E_02.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Zootopia_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/2049.Blade.Runner_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/2049.Blade.Runner_02.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/American.Dreams.in.China_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Biri.Girl_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Bohemian.Rhapsody_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Bohemian.Rhapsody_02.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Bohemian.Rhapsody_03.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Crouching.Tiger.Hidden.Dragon.2000_01.webp,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Detachment_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Detachment_02.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Gisaengchung_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Iron.Man_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Kureyon.Shinchan_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Love.Actually_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Roman.Holiday_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Roman.Holiday_02.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Sherlock.S01_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/The.Secret.Life.of.Walter.Mitty_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Youth.Over.Flowers.in.Africa_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Youth.Over.Flowers.in.Africa_02.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/My.Mister_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/One.Day_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/One.Day_02.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/One.Day_03.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Ready.Player.One_02.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Begin.Again_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Begin.Again_02.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/Freddie_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/naruto.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/SetoNaikai_01.jpg,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/yexiu_01.png,https://cdn.jsdelivr.net/gh/tiancixiong/BlogIMG@230521/theme/cover/yexiu_02_FUJISKYTREE.png".split(",");
  var bgindex = Math.floor(Math.random()*bg.length);
  if (!!window.ActiveXObject || "ActiveXObject" in window) { //is IE?
    alert('朋友，IE浏览器未适配哦~');
  }
  </script>
  <style type="text/css">
  .hljs-ln{border-collapse:collapse}.hljs-ln td{padding:0}.hljs-ln-n:before{content:attr(data-line-number)}
  </style>
  <style type="text/css">.site-top .lower nav{display:block !important;}.author-profile i,.post-like a,.post-share .show-share,.sub-text,.we-info a,span.sitename,.post-more i:hover,#pagination a:hover,.post-content a:hover,.float-content i:hover{color:#FE9600}.feature i,.download,.navigator i:hover,.links ul li:before,.ar-time i,span.ar-circle,.object,.comment .comment-reply-link,.siren-checkbox-radio:checked + .siren-checkbox-radioInput:after{background:#FE9600}::-webkit-scrollbar-thumb{background:#FE9600}.download,.navigator i:hover,.link-title,.links ul li:hover,#pagination a:hover,.comment-respond input[type='submit']:hover{border-color:#FE9600}.entry-content a:hover,.site-info a:hover,.comment h4 a,#comments-navi a.prev,#comments-navi a.next,.comment h4 a:hover,.site-top ul li a:hover,.entry-title a:hover,#archives-temp h3,span.page-numbers.current,.sorry li a:hover,.site-title a:hover,i.iconfont.js-toggle-search.iconsearch:hover,.comment-respond input[type='submit']:hover{color:#FE9600}.comments .comments-main{display:block !important;}.comments .comments-hidden{display:none !important;}background-position:center center;background-attachment:inherit;}
  </style>
</head>
</html>
<body class="page-template page-template-user page-template-page-analytics page-template-userpage-analytics-php page page-id-1297 chinese-font serif isWebKit">
  <div class="scrollbar" id="bar">
  </div>
  <a href="#" class="cd-top faa-float animated"></a>
  <section id="main-container">
    <div class="headertop filter-dot">
  <!--首页背景图下方的波浪线-->
  <!--<div id="banner_wave_1"></div>-->
  <!--<div id="banner_wave_2"></div>-->
  <figure id="centerbg" class="centerbg">
    <div class="focusinfo no-select">
      <div class="header-tou">
        <a href="/">
          <img src="https://fastly.jsdelivr.net/gh/tiancixiong/cdn@v1.0/img/custom/avatar.jpg">
        </a>
      </div>
      <div class="header-info">
        <p>You Only Live Once</p>
        <div class="top-social_v2">
          <li id="bg-pre">
            <img class="flipx" src="https://cdn.jsdelivr.net/gh/tiancixiong/cdn@sakura-theme/img/other/next-b.svg">
          </li>
          
            
              
                <li>
                  <a href="https://github.com/tiancixiong" target="_blank" class="social-github" title="github">
                    <img src="https://fastly.jsdelivr.net/gh/tiancixiong/cdn@v1.0/img/social/github.png">
                  </a>
                </li>
              
            
              
                <li>
                  <a href="mailto:support@xiongtianci.com" target="_blank" class="social-github" title="E-mail">
                    <img src="https://fastly.jsdelivr.net/gh/tiancixiong/cdn@v1.0/img/social/email.svg">
                  </a>
                </li>
              
            
          
          <li id="bg-next">
            <img src="https://cdn.jsdelivr.net/gh/tiancixiong/cdn@sakura-theme/img/other/next-b.svg">
          </li>
        </div>
      </div>
    </div>
  </figure>
  <div id="video-container" style="">
    <video style="object-fit: fill" id="bgvideo" class="video" video-name="" src="" width="auto" preload="auto">
    </video>
    <div id="video-btn" class="loadvideo videolive">
    </div>
    <div id="video-add">
    </div>
    <div class="video-stu">
    </div>
  </div>
  <div class="headertop-down faa-float animated" onclick="headertop_down()">
    <span>
      <i class="fa fa-chevron-down" aria-hidden="true">
      </i>
    </span>
  </div>
</div>
    <div id="page" class="site wrapper">
      <header class="site-header no-select gizle sabit" role="banner">
  <div class="site-top">
    <div class="site-branding">
      <span class="site-title">
        <span class="logolink moe-mashiro">
          <a href="/">
            <span class="sakurasono"></span>
            <span class="shironeko">天赐の小站</span>
          </a>
        </span>
      </span>
    </div>
    <div class="searchbox search-form-submit">
      <i class="iconfont js-toggle-search iconsearch icon-search">
      </i>
    </div>
    <div id="show-nav" class="showNav mobile-fit">
      <div class="line line1">
      </div>
      <div class="line line2">
      </div>
      <div class="line line3">
      </div>
    </div>
    <div class="lower-cantiner">
      <div class="lower">
        <nav class="mobile-fit-control hide">
          <ul id="menu-new" class="menu">
            
              <li>
                <a href="/">
                  <span class="faa-parent animated-hover">
                    <i class="fa  fa-fort-awesome faa-horizontal" aria-hidden="true"></i>
                    首页
                  </span>
                </a>
                
              </li>
            
              <li>
                <a href="/archives">
                  <span class="faa-parent animated-hover">
                    <i class="fa  fa-terminal faa-vertical" aria-hidden="true"></i>
                    极客
                  </span>
                </a>
                
                  <ul class="sub-menu">
                    
                      <li>
                        <a href="/categories/技术/">
                          <i class="fa fa-code" aria-hidden="true"></i>
                          技术
                        </a>
                      </li>
                    
                      <li>
                        <a href="/categories/Linux/">
                          <i class="fa fa-linux" aria-hidden="true"></i>
                          Linux
                        </a>
                      </li>
                    
                  </ul>
                
              </li>
            
              <li>
                <a href="/archives">
                  <span class="faa-parent animated-hover">
                    <i class="fa  fa-slack faa-spin" aria-hidden="true"></i>
                    爱好
                  </span>
                </a>
                
                  <ul class="sub-menu">
                    
                      <li>
                        <a href="/categories/电影/">
                          <i class="fa fa-film" aria-hidden="true"></i>
                          电影
                        </a>
                      </li>
                    
                      <li>
                        <a href="/categories/日语/">
                          <i class="fa fa-language" aria-hidden="true"></i>
                          日语
                        </a>
                      </li>
                    
                  </ul>
                
              </li>
            
              <li>
                <a href="/archives">
                  <span class="faa-parent animated-hover">
                    <i class="fa  fa-archive faa-ring" aria-hidden="true"></i>
                    归档
                  </span>
                </a>
                
                  <ul class="sub-menu">
                    
                      <li>
                        <a href="/categories/生活/">
                          <i class="fa fa-file-text-o" aria-hidden="true"></i>
                          生活
                        </a>
                      </li>
                    
                      <li>
                        <a href="/categories/随想/">
                          <i class="fa fa-commenting-o" aria-hidden="true"></i>
                          随想
                        </a>
                      </li>
                    
                      <li>
                        <a href="/categories/资源/">
                          <i class="fa fa-cloud-download" aria-hidden="true"></i>
                          资源
                        </a>
                      </li>
                    
                      <li>
                        <a href="/categories/转载/">
                          <i class="fa fa-book" aria-hidden="true"></i>
                          转载
                        </a>
                      </li>
                    
                  </ul>
                
              </li>
            
              <li>
                <a href="/comment/">
                  <span class="faa-parent animated-hover">
                    <i class="fa  fa-pencil-square-o faa-tada" aria-hidden="true"></i>
                    留言板
                  </span>
                </a>
                
              </li>
            
              <li>
                <a href="/links/">
                  <span class="faa-parent animated-hover">
                    <i class="fa  fa-link faa-shake" aria-hidden="true"></i>
                    友人帐
                  </span>
                </a>
                
              </li>
            
              <li>
                <a href="/donate/">
                  <span class="faa-parent animated-hover">
                    <i class="fa  fa-heart faa-burst" aria-hidden="true"></i>
                    赞赏
                  </span>
                </a>
                
              </li>
            
              <li>
                <a href="/">
                  <span class="faa-parent animated-hover">
                    <i class="fa  fa-leaf faa-falling" aria-hidden="true"></i>
                    关于
                  </span>
                </a>
                
                  <ul class="sub-menu">
                    
                      <li>
                        <a href="/about/">
                          <i class="fa fa-meetup" aria-hidden="true"></i>
                          我？
                        </a>
                      </li>
                    
                      <li>
                        <a href="/theme-sakura/">
                          <i class="fa iconfont icon-sakura" aria-hidden="true"></i>
                          主题
                        </a>
                      </li>
                    
                  </ul>
                
              </li>
            
              <li>
                <a href="/atom.xml">
                  <span class="faa-parent animated-hover">
                    <i class="fa  fa-rss faa-passing" aria-hidden="true"></i>
                    RSS
                  </span>
                </a>
                
              </li>
            
          </ul>
        </nav>
      </div>
    </div>
  </div>
</header>

      <link rel="stylesheet" type="text/css" href="/css/sharejs.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.4.2/tocbot.css">
<div class="pattern-center-blank"></div>

  <div class="pattern-center single-center">
    <!-- 有配图默认渲染第一张 -->
    <div class="pattern-attachment-img lazyload" style="background-image: url(https://images.unsplash.com/photo-1528164344705-47542687000d?w=540);" src="https://fastly.jsdelivr.net/gh/tiancixiong/cdn@v1.0/img/loader/orange.progress-bar-stripe-loader.svg" data-src="https://images.unsplash.com/photo-1528164344705-47542687000d?w=540">
    </div>
    <header class="pattern-header single-header">
      <h1 class="entry-title">
      JUC学习笔记-基础并发工具：Atomic包与CAS</h1>
      <p class="entry-census">
        <span>
          <a href="https://blog.xiongtianci.com">
            <img src="https://cdn.jsdelivr.net/gh/tiancixiong/cdn@v1.0/img/custom/avatar.jpg">
          </a>
        </span>
        <span>
          <a href="https://blog.xiongtianci.com">木浅</a>
        </span>
        <span class="bull">
        ·</span>
        2024-4-2<span class="bull">
        ·</span>
      <span id="busuanzi_value_page_pv"></span>次阅读</p>
    </header>
  </div>

<div id="content" class="site-content">
  <div id="primary" class="content-area">
    <main id="main" class="site-main" role="main">
      <article id="post-1" class="post-1 post type-post status-publish format-standard has-post-thumbnail hentry category-uncategorized">
        <div class="toc"></div>
        <!--<div class="toc-entry-content"><!-- 套嵌目录使用（主要为了支援评论）-->
        
        <div class="entry-content">
          <h1 id="Atomic包与CAS概述"><a href="#Atomic包与CAS概述" class="headerlink" title="Atomic包与CAS概述"></a>Atomic包与CAS概述</h1><p>1、<strong>什么是Atomic包</strong></p>
<p><code>java.util.concurrent.atomic</code> 包是Java提供的一组线程安全的原子操作类，可以在不使用锁的情况下实现线程安全操作。这些类主要分为以下几类：</p>
<ul>
<li>基本类型：<code>AtomicInteger</code>、<code>AtomicLong</code>、<code>AtomicBoolean</code></li>
<li>引用类型：<code>AtomicReference</code>、<code>AtomicStampedReference</code>、<code>AtomicMarkableReference</code></li>
<li>数组类型：<code>AtomicIntegerArray</code>、<code>AtomicLongArray</code>、<code>AtomicReferenceArray</code></li>
<li>累加器：<code>LongAdder</code>、<code>DoubleAdder</code>（Java 8+）</li>
</ul>
<p>2、<strong>什么是CAS</strong></p>
<p>CAS（Compare-And-Swap）是一种无锁算法，包含三个操作数：</p>
<ul>
<li>内存位置（V）</li>
<li>预期原值（A）</li>
<li>新值（B）</li>
</ul>
<p>CAS操作逻辑：当且仅当V的值等于A时，才会将V的值更新为B，否则不执行任何操作。无论哪种情况，都会返回V的当前值。</p>
<h2 id="Atomic类和CAS的关系"><a href="#Atomic类和CAS的关系" class="headerlink" title="Atomic类和CAS的关系"></a>Atomic类和CAS的关系</h2><p>Java 的 <code>java.util.concurrent.atomic</code> 包中的所有原子类（如 <code>AtomicInteger</code>、<code>AtomicReference</code>）底层均基于 <strong>CAS 机制</strong> 实现。</p>
<ul>
<li><strong>Atomic类</strong> 是暴露给开发者使用的 <strong>工具</strong>。</li>
<li><strong>CAS</strong> 是这些工具背后的 <strong>核心算法</strong>。</li>
</ul>
<pre><code class="java">// AtomicInteger 的源码片段（JDK）
public final int incrementAndGet() {
    return U.getAndAddInt(this, VALUE, 1) + 1;
}
// 最终调用的是Unsafe类的CAS操作：
unsafe.compareAndSwapInt(obj, offset, expect, update);
</code></pre>
<p>Atomic 包的 <strong>所有能力</strong> 均围绕 CAS 展开：</p>
<ul>
<li><strong>原子自增</strong>：<code>AtomicInteger.getAndIncrement()</code> → CAS 循环</li>
<li><strong>条件更新</strong>：<code>AtomicReference.compareAndSet()</code> → 直接调用 CAS</li>
<li><strong>复杂累加</strong>：<code>LongAdder</code> → 分段 CAS 优化</li>
</ul>
<pre><code class="java">AtomicInteger counter = new AtomicInteger(0);

// 底层CAS实现伪代码：
int oldValue;
do {
    oldValue = counter.get(); // 读取当前值
} while (!counter.compareAndSet(oldValue, oldValue + 1)); // CAS尝试更新
</code></pre>
<p>所有使用 Atomic 类的场景都隐含了 CAS 的参与：</p>
<ol>
<li><p>计数器</p>
<pre><code class="java">// 高并发环境下的计数器
AtomicInteger count = new AtomicInteger();
count.incrementAndGet(); // 内部用CAS保证线程安全
</code></pre>
</li>
<li><p>状态标志</p>
<pre><code class="java">// 无锁实现状态切换
AtomicBoolean isRunning = new AtomicBoolean(true);
isRunning.compareAndSet(true, false); // CAS更新
</code></pre>
</li>
<li><p>非阻塞算法</p>
<pre><code class="java">// 实现无锁栈（Treiber算法）
AtomicReference&lt;Node&lt;E&gt;&gt; top = new AtomicReference&lt;&gt;();
public void push(E item) {
    Node&lt;E&gt; newHead = new Node&lt;&gt;(item);
    Node&lt;E&gt; oldHead;
    do {
        oldHead = top.get();
        newHead.next = oldHead;
    } while (!top.compareAndSet(oldHead, newHead)); // CAS更新栈顶
}
</code></pre>
</li>
</ol>
<h1 id="核心源码"><a href="#核心源码" class="headerlink" title="核心源码"></a>核心源码</h1><p>1、AtomicInteger实现原理</p>
<pre><code class="java">public class AtomicInteger extends Number implements java.io.Serializable {
    private static final long serialVersionUID = 6214790243416807050L;

    // 获取Unsafe实例
    private static final Unsafe unsafe = Unsafe.getUnsafe();
    private static final long valueOffset;

    static {
        try {
            // 获取value字段的内存偏移地址
            valueOffset = unsafe.objectFieldOffset
                (AtomicInteger.class.getDeclaredField(&quot;value&quot;));
        } catch (Exception ex) { throw new Error(ex); }
    }

    private volatile int value;

    // CAS核心方法
    public final boolean compareAndSet(int expect, int update) {
        return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
    }

    // 原子自增
    public final int incrementAndGet() {
        return unsafe.getAndAddInt(this, valueOffset, 1) + 1;
    }
}
</code></pre>
<p>2、Unsafe类的CAS操作</p>
<p>Atomic类底层依赖 <code>sun.misc.Unsafe</code> 类的CAS操作：</p>
<pre><code class="java">// Unsafe类提供了多种CAS方法
// 对象字段的CAS操作
public final native boolean compareAndSwapObject(Object o, long offset, Object expected, Object x);
public final native boolean compareAndSwapInt(Object o, long offset, int expected, int x);
public final native boolean compareAndSwapLong(Object o, long offset, long expected, long x);
</code></pre>
<p>参数说明：</p>
<ul>
<li><code>o</code>: 要操作的对象</li>
<li><code>offset</code>: 字段在对象中的偏移量(内存地址)</li>
<li><code>expected</code>: 期望的当前值</li>
<li><code>x</code>: 要设置的新值</li>
</ul>
<h1 id="基础使用"><a href="#基础使用" class="headerlink" title="基础使用"></a>基础使用</h1><p><strong>计数器场景</strong></p>
<pre><code class="java">// 传统同步方式
class Counter {
    private int count = 0;
    public synchronized void increment() {
        count++;
    }
}

// Atomic方式
class AtomicCounter {
    private AtomicInteger count = new AtomicInteger(0);
    public void increment() {
        count.incrementAndGet();
    }
    // 更灵活的操作
    public void add(int delta) {
        count.getAndAdd(delta);
    }
}
</code></pre>
<p><strong>状态标志控制</strong></p>
<pre><code class="java">import java.util.concurrent.atomic.AtomicBoolean;

// 系统开关控制
public class FeatureToggle {
    private AtomicBoolean enabled = new AtomicBoolean(false);

    public void enable() {
        enabled.set(true);
    }

    public void disable() {
        enabled.set(false);
    }

    public boolean isEnabled() {
        return enabled.get();
    }

    // 安全切换状态
    public boolean toggle() {
        boolean prev;
        do {
            prev = enabled.get();
        } while (!enabled.compareAndSet(prev, !prev));
        return !prev;
    }
}
</code></pre>
<p><strong>库存扣减（电商场景）</strong></p>
<pre><code class="java">import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;

public class InventorySystem {
    private AtomicInteger stock = new AtomicInteger(1000); // 总库存

    public boolean deductStock(int quantity) {
        int current;
        do {
            current = stock.get();
            if (current &lt; quantity) {
                return false; // 库存不足
            }
        } while (!stock.compareAndSet(current, current - quantity));

        // 扣减成功，处理订单逻辑

        return true;
    }

    // 测试用例
    public static void main(String[] args) {
        InventorySystem inventory = new InventorySystem();
        // 模拟100个线程并发扣减
        IntStream.range(0, 100).parallel().forEach(i -&gt; {
            if (inventory.deductStock(1)) {
                System.out.println(&quot;扣减成功&quot;);
            }
        });
        System.out.println(&quot;剩余库存: &quot; + inventory.stock.get());
    }
}
</code></pre>
<p><strong>序列号生成（分布式ID）</strong></p>
<pre><code class="java">import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;

public class SequenceGenerator {
    private final AtomicLong sequence = new AtomicLong(0);

    public long nextId() {
        return sequence.getAndIncrement();
    }

    // 生成带时间戳的订单ID（格式：时间戳 + 6位序列号）
    public String generateOrderId() {
        long timestamp = System.currentTimeMillis();
        long seq = nextId();
        return String.format(&quot;%d%06d&quot;, timestamp, seq % 1_000_000);
    }
}

class SequenceGeneratorTest {
    private static final SequenceGenerator generator = new SequenceGenerator();
    private static final Set&lt;String&gt; generatedIds = ConcurrentHashMap.newKeySet(); // 线程安全的Set
    private static final int THREAD_COUNT = 100; // 并发线程数
    private static final int REQUESTS_PER_THREAD = 1000; // 每个线程生成ID的数量

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT);
        CountDownLatch latch = new CountDownLatch(THREAD_COUNT);

        long startTime = System.currentTimeMillis();

        // 提交任务
        for (int i = 0; i &lt; THREAD_COUNT; i++) {
            executor.submit(() -&gt; {
                try {
                    for (int j = 0; j &lt; REQUESTS_PER_THREAD; j++) {
                        String orderId = generator.generateOrderId();
                        if (!generatedIds.add(orderId)) {
                            System.err.println(&quot;⚠️ 重复ID: &quot; + orderId);
                        }
                    }
                } finally {
                    latch.countDown();
                }
            });
        }

        // 等待所有线程完成
        latch.await();
        executor.shutdown();

        long totalTime = System.currentTimeMillis() - startTime;
        int totalIds = THREAD_COUNT * REQUESTS_PER_THREAD;

        System.out.println(&quot;测试完成！&quot;);
        System.out.println(&quot;生成ID总数: &quot; + totalIds);
        System.out.println(&quot;唯一ID数量: &quot; + generatedIds.size());
        System.out.println(&quot;是否有重复: &quot; + (generatedIds.size() != totalIds ? &quot;是&quot; : &quot;否&quot;));
        System.out.println(&quot;总耗时: &quot; + totalTime + &quot;ms&quot;);
        System.out.println(&quot;QPS: &quot; + (totalIds * 1000L / totalTime));
    }
}
</code></pre>
<p><strong>实时报价系统</strong></p>
<pre><code class="java">public class PriceUpdater {
    private AtomicReference&lt;BigDecimal&gt; currentPrice = 
        new AtomicReference&lt;&gt;(BigDecimal.ZERO);

    // 多个行情源同时更新价格
    public void updatePrice(BigDecimal newPrice) {
        BigDecimal current;
        do {
            current = currentPrice.get();
            if (newPrice.compareTo(current) &lt;= 0) {
                return; // 新价格不比当前高，不更新
            }
        } while (!currentPrice.compareAndSet(current, newPrice));

        // 价格更新通知
        notifySubscribers(newPrice);
    }

    private void notifySubscribers(BigDecimal price) {
        // 通知订阅者逻辑...
    }
}
</code></pre>
<h1 id="CAS的局限性及解决方案"><a href="#CAS的局限性及解决方案" class="headerlink" title="CAS的局限性及解决方案"></a>CAS的局限性及解决方案</h1><h2 id="ABA问题"><a href="#ABA问题" class="headerlink" title="ABA问题"></a>ABA问题</h2><p><strong>问题描述</strong>：线程1读取值为A，线程2将值改为B后又改回A，此时线程1的CAS操作仍会成功，可能导致逻辑错误。</p>
<pre><code class="java">AtomicReference&lt;Integer&gt; account = new AtomicReference&lt;&gt;(100);

// 线程1 (会遭遇ABA问题)
new Thread(() -&gt; {
    int current = account.get(); // 读取100
    System.out.println(&quot;线程1读取: &quot; + current);

    // 模拟处理其他事情时被挂起
    try { Thread.sleep(1000); } catch (InterruptedException e) {}

    // 尝试更新
    boolean success = account.compareAndSet(current, 200);
    System.out.println(&quot;线程1更新结果: &quot; + success + &quot;，当前值: &quot; + account.get());
}).start();

// 线程2 (制造ABA场景)
new Thread(() -&gt; {
    // 第一次修改：100→50
    boolean success1 = account.compareAndSet(100, 50);
    System.out.println(&quot;线程2第一次修改: &quot; + success1 + &quot;，当前值: &quot; + account.get());

    // 第二次修改：50→100
    boolean success2 = account.compareAndSet(50, 100);
    System.out.println(&quot;线程2第二次修改: &quot; + success2 + &quot;，当前值: &quot; + account.get());
}).start();
</code></pre>
<p><strong>银行账户转账中的ABA问题</strong>：</p>
<p>在银行转账场景中，假设账户余额为100元：</p>
<ol>
<li>线程A读取余额为100，准备转账50元</li>
<li>线程A被挂起</li>
<li>线程B转账50元，余额变为50</li>
<li>线程C存入50元，余额又变回100</li>
<li>线程A恢复执行，发现余额还是100，认为没有变化，执行转账操作</li>
</ol>
<p>这样会导致账户实际上被扣款两次（线程B和线程A都扣款了50元），但余额看起来只减少了50元。</p>
<p><strong>解决方案</strong>：使用 <code>AtomicStampedReference</code> 或 <code>AtomicMarkableReference</code> 添加版本号控制。</p>
<p><code>AtomicStampedReference</code> 通过添加一个版本号（stamp）来解决ABA问题。每次修改都会递增版本号，CAS操作不仅要比较值，还要比较版本号。</p>
<pre><code class="java">import java.util.concurrent.atomic.AtomicStampedReference;

// 银行账户转账ABA问题示例
public class Account {
    // 使用AtomicStampedReference包装余额，初始值100，初始版本号0
    private AtomicStampedReference&lt;Integer&gt; balance = 
        new AtomicStampedReference&lt;&gt;(100, 0);

    public boolean transfer(int amount) {
        int[] stamp = new int[1]; // 用于保存当前版本号的数组
        int current;
        do {
            // 获取当前值和版本号
            current = balance.get(stamp);
            if (current &lt; amount) {
                return false; // 余额不足，转账失败
            }
        } while (!balance.compareAndSet(
            current, current - amount,  // 期望值和新值
            stamp[0], stamp[0] + 1)); // 期望版本号和新版本号
        return true;
    }
}
</code></pre>
<ul>
<li>使用 <code>get(stamp)</code> 同时获取当前值和版本号</li>
<li><code>compareAndSet()</code> 只有当值和版本号都匹配时才更新</li>
</ul>
<hr>
<p><code>AtomicStampedReference</code> 和 <code>AtomicMarkableReference</code> 都是 Java 并发包中用于解决 <strong>ABA 问题</strong> 的原子引用类</p>
<table>
<thead>
<tr>
<th style="text-align:left">特性</th>
<th style="text-align:left"><code>AtomicStampedReference</code></th>
<th style="text-align:left"><code>AtomicMarkableReference</code></th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left"><strong>版本控制方式</strong></td>
<td style="text-align:left">使用 <strong>整数版本号（stamp）</strong>（每次修改递增）</td>
<td style="text-align:left">使用 <strong>布尔标记（mark）</strong>（true/false）</td>
</tr>
<tr>
<td style="text-align:left"><strong>适用场景</strong></td>
<td style="text-align:left">需要严格版本控制的场景（如银行交易）</td>
<td style="text-align:left">只需知道”是否被修改过”的场景（如缓存标记）</td>
</tr>
<tr>
<td style="text-align:left"><strong>ABA 问题解决方案</strong></td>
<td style="text-align:left">通过版本号检测中间变化</td>
<td style="text-align:left">通过布尔标记检测是否被修改过</td>
</tr>
<tr>
<td style="text-align:left"><strong>典型用例</strong></td>
<td style="text-align:left">账户余额、计数器</td>
<td style="text-align:left">对象状态标记、缓存失效机制</td>
</tr>
</tbody>
</table>
<p>AtomicStampedReference 适用场景：</p>
<ul>
<li>银行账户余额（防止 ABA 问题）</li>
<li>计数器（需要知道修改次数）</li>
<li>任何需要 <strong>精确版本控制</strong> 的场景</li>
</ul>
<pre><code class="java">AtomicStampedReference&lt;Integer&gt; account = new AtomicStampedReference&lt;&gt;(100, 0);

// 线程1：读取值和版本号
int[] stamp = new int[1];
int balance = account.get(stamp); // balance=100, stamp[0]=0

// 线程2：修改值并增加版本号
account.compareAndSet(100, 50, 0, 1); // 版本号 0→1

// 线程1尝试更新（失败，因为版本号已变）
boolean success = account.compareAndSet(100, 200, stamp[0], stamp[0] + 1);
// success = false（因为版本号已变为1，不匹配0）
</code></pre>
<p>AtomicMarkableReference 适用场景：</p>
<ul>
<li>缓存数据是否失效（true=失效，false=有效）</li>
<li>对象是否被锁定（true=已锁定，false=未锁定）</li>
<li>只需知道 <strong>“对象是否被修改过”</strong>，而不关心修改了多少次</li>
</ul>
<pre><code class="java">AtomicMarkableReference&lt;String&gt; cache = new AtomicMarkableReference&lt;&gt;(&quot;data&quot;, false);

// 线程1：读取值和标记
boolean[] mark = new boolean[1];
String data = cache.get(mark); // data=&quot;data&quot;, mark[0]=false

// 线程2：修改值并设置标记为 true（表示已修改）
cache.compareAndSet(&quot;data&quot;, &quot;newData&quot;, false, true);

// 线程1尝试更新（失败，因为标记已变）
boolean success = cache.compareAndSet(&quot;data&quot;, &quot;updated&quot;, mark[0], true);
// success = false（因为标记已变为 true，不匹配 false）
</code></pre>
<p><strong>如何选择？</strong></p>
<table>
<thead>
<tr>
<th style="text-align:left">场景</th>
<th style="text-align:left">推荐类</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left"><strong>需要严格版本控制</strong>（如金融交易）</td>
<td style="text-align:left"><code>AtomicStampedReference</code></td>
</tr>
<tr>
<td style="text-align:left"><strong>只需知道是否被修改过</strong>（如缓存失效）</td>
<td style="text-align:left"><code>AtomicMarkableReference</code></td>
</tr>
</tbody>
</table>
<h2 id="自旋开销"><a href="#自旋开销" class="headerlink" title="自旋开销"></a>自旋开销</h2><p><strong>问题描述</strong>：高并发场景下CAS失败率增加，线程会持续自旋，导致CPU空转。</p>
<pre><code class="java">public class Counter {
    private AtomicInteger count = new AtomicInteger(0);

    public void increment() {
        int oldValue;
        do {
            oldValue = count.get();
        } while (!count.compareAndSet(oldValue, oldValue + 1));
    }
}
// 高并发时可能导致大量线程自旋
</code></pre>
<p><strong>解决方案</strong>：</p>
<ul>
<li>使用 <code>LongAdder</code> 替代 <code>AtomicLong</code>（Java 8+）</li>
<li>引入适当的退避策略</li>
</ul>
<pre><code class="java">// 高并发计数器优化
public class HitCounter {
    // 使用 LongAdder 作为计数器
    private LongAdder count = new LongAdder();

    // 增加计数
    public void hit() {
        count.increment();
    }

    // 获取总计数
    public long getCount() {
        return count.sum();
    }
}
</code></pre>
<p><code>LongAdder</code> 采用了 <strong>分段累加（Cell 分散）</strong> 的策略：</p>
<ol>
<li><strong>基础值（base）</strong>：初始计数值</li>
<li><strong>Cell 数组</strong>：当竞争激烈时，会创建多个 Cell，让不同线程更新不同的 Cell</li>
<li><strong>最终求和</strong>：<code>sum()</code> 方法返回 base + 所有 Cell 的和</li>
</ol>
<p><strong>退避算法（Exponential Backoff）</strong></p>
<pre><code class="java">public class BackoffCounter {
    private AtomicInteger count = new AtomicInteger(0);
    // 最小退避时间(单位毫秒)
    private static final int MIN_DELAY = 1;
    // 最大退避时间(单位毫秒)，防止退避时间无限增长
    private static final int MAX_DELAY = 100;

    public void increment() {
        int delay = MIN_DELAY; // 初始退避时间
        while (true) {
            int current = count.get();
            if (count.compareAndSet(current, current + 1)) {
                break; // CAS成功，退出循环
            }
            // CAS失败后等待随机时间
            try {
                Thread.sleep((long)(Math.random() * delay));
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            delay = Math.min(delay * 2, MAX_DELAY); // 指数增加退避时间
        }
    }
}
</code></pre>
<p>指数退避算法：每次失败后，等待时间按指数增长：1, 2, 4, 8,…直到MAX_DELAY</p>
<h2 id="只能保证单个变量原子性"><a href="#只能保证单个变量原子性" class="headerlink" title="只能保证单个变量原子性"></a>只能保证单个变量原子性</h2><p><strong>问题描述</strong>：<br>CAS无法保证多个变量的原子更新。</p>
<p><strong>解决方案</strong>：</p>
<ul>
<li>使用<code>AtomicReference</code>包装多个变量</li>
<li>使用锁机制</li>
</ul>
<pre><code class="java">// 原子更新多个变量
public class Point {
    private static class State {
        final int x;
        final int y;
        State(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }

    // 原子状态引用
    private AtomicReference&lt;State&gt; state = 
        new AtomicReference&lt;&gt;(new State(0, 0));

    // 原子更新方法
    public void move(int deltaX, int deltaY) {
        State current;
        State newState;
        do {
            current = state.get(); // 获取当前状态
            newState = new State(  // 创建新状态
                current.x + deltaX, 
                current.y + deltaY
            );
        } while (!state.compareAndSet(current, newState));
    }

    public int getX() {
        return state.get().x;
    }
    public int getY() {
        return state.get().y;
    }
}
</code></pre>
<ul>
<li><code>State</code>类被设计为<strong>不可变(immutable)</strong>的，所有字段都是<code>final</code>的，一旦创建就不能修改</li>
</ul>
<h1 id="性能对比与选型建议"><a href="#性能对比与选型建议" class="headerlink" title="性能对比与选型建议"></a>性能对比与选型建议</h1><p>1、Atomic vs Synchronized</p>
<pre><code class="java">// 性能测试对比
public class PerformanceTest {
    private AtomicInteger atomicCounter = new AtomicInteger(0);
    private int syncCounter = 0;

    @Test
    public void testPerformance() {
        // Atomic测试
        long atomicTime = test(() -&gt; {
            atomicCounter.incrementAndGet();
        });

        // Synchronized测试
        long syncTime = test(() -&gt; {
            synchronized (this) {
                syncCounter++;
            }
        });

        System.out.printf(&quot;Atomic: %dms, Synchronized: %dms%n&quot;, 
            atomicTime, syncTime);
    }

    private long test(Runnable task) {
        long start = System.currentTimeMillis();
        IntStream.range(0, 1_000_000)
            .parallel()
            .forEach(i -&gt; task.run());
        return System.currentTimeMillis() - start;
    }
}
</code></pre>
<p>2、选型建议</p>
<table>
<thead>
<tr>
<th style="text-align:left">场景</th>
<th style="text-align:left">推荐方案</th>
<th style="text-align:left">理由</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">简单计数器</td>
<td style="text-align:left"><code>AtomicInteger/Long</code></td>
<td style="text-align:left">实现简单，性能好</td>
</tr>
<tr>
<td style="text-align:left">高并发统计</td>
<td style="text-align:left"><code>LongAdder</code></td>
<td style="text-align:left">减少CAS竞争</td>
</tr>
<tr>
<td style="text-align:left">复杂对象更新</td>
<td style="text-align:left"><code>AtomicReference</code></td>
<td style="text-align:left">保证引用原子性</td>
</tr>
<tr>
<td style="text-align:left">需要版本控制</td>
<td style="text-align:left"><code>AtomicStampedReference</code></td>
<td style="text-align:left">解决ABA问题</td>
</tr>
<tr>
<td style="text-align:left">多变量原子更新</td>
<td style="text-align:left">锁机制</td>
<td style="text-align:left">CAS无法直接支持</td>
</tr>
</tbody>
</table>

        </div>
        <!-- .entry-content -->
        <div class="single-reward">
          <div class="reward-open">赏<div class="reward-main">
              <ul class="reward-row">
                <li class="alipay-code"><img src="https://fastly.jsdelivr.net/gh/tiancixiong/cdn@v1.0/img/custom/donate/AliPayQR.jpg"></li>
                <li class="wechat-code"><img src="https://fastly.jsdelivr.net/gh/tiancixiong/cdn@v1.0/img/custom/donate/WeChanQR.png"></li>
              </ul>
            </div>
          </div>
        </div>
        <div style="text-align:center; width: 100%" class="social-share share-mobile" data-disabled="diandian, tencent"></div>
        <footer class="post-footer">
          <div class="post-lincenses"><a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" target="_blank" rel="nofollow"><i class="fa fa-creative-commons" aria-hidden="true"></i> 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议</a></div>
          <div class="post-tags">
          </div>
          <div class="post-share">
            <div class="social-share sharehidden share-component"></div>
            <i class="iconfont show-share icon-forward"></i>
          </div>
        </footer><!-- .entry-footer -->
      </article>
      <!-- #post-## -->
      <!--<div class="toc" style="background: none;"></div>-->
      <section class="post-squares nextprev">
        
          
            <div class="post-nepre half previous">
          
            <a href="/2024/04/03/JUC学习笔记-显式锁：ReentrantLock详解/" rel="prev">
              <div class="background">
                <img class="lazyload" src="https://fastly.jsdelivr.net/gh/tiancixiong/cdn@v1.0/img/loader/orange.progress-bar-stripe-loader.svg" data-src="https://images.unsplash.com/photo-1528164344705-47542687000d?w=540" style="width: 100%; height: 100%; object-fit: cover; pointer-events: none;" onerror="imgError(this,3)" src="https://images.unsplash.com/photo-1528164344705-47542687000d?w=540">
              </div>
              <span class="label">
              Previous Post</span>
              <div class="info">
                <h3>
                JUC学习笔记-显式锁：ReentrantLock详解</h3>
                <hr>
              </div>
            </a>
          </div>
        
        
          
            <div class="post-nepre half next">
          
            <a href="/2024/04/01/JUC学习步骤/" rel="next">
              <div class="background">
                <img class="lazyload" src="https://fastly.jsdelivr.net/gh/tiancixiong/cdn@v1.0/img/loader/orange.progress-bar-stripe-loader.svg" data-src="https://images.unsplash.com/photo-1528164344705-47542687000d?w=540" style="width: 100%; height: 100%; object-fit: cover; pointer-events: none;" onerror="imgError(this,3)" src="https://images.unsplash.com/photo-1528164344705-47542687000d?w=540">
              </div>
              <span class="label">
              Next Post</span>
              <div class="info">
                <h3>
                JUC学习步骤</h3>
                <hr>
              </div>
            </a>
          </div>
        
      </section>
      <!-- 评论插件valine -->

<div id="vcomments"></div>
<script>
  window.onload = function(){
      var valine = new Valine();
      valine.init({
        el: '#vcomments',
        appId: "VeenC2gYYyfSOq2rcCSmmruy-MdYXbMMI",
        appKey: "F5kjyHdh4akqc7SDmfzQP8Qi",
		notify: false,
		verify: false,
        path: window.location.pathname,
        placeholder: "你是我一生只会遇见一次的惊喜 ...",
		avatar: "monsterid",
		//meta: [nick,mail,link],
		visitor: true,
        recordIP: "true",
		pageSize: "5" || 10,
		serverURLs: "https://VeenC2gY.api.lncldglobal.com"
      });
	//增加以下六行代码去除 power by valine
    var infoEle = document.querySelector('#vcomments .info');
    if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0){
      infoEle.childNodes.forEach(function(item) {
        item.parentNode.removeChild(item);
      });
    }
  }
</script>

      <section class="author-profile">
        <div class="info" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
          <a href="https://blog.xiongtianci.com" class="profile gravatar"><img src="https://cdn.jsdelivr.net/gh/tiancixiong/cdn@v1.0/img/custom/avatar.jpg" itemprop="image" alt="木浅" height="70" width="70"></a>
          <div class="meta">
            <span class="title">Author</span>
            <h3 itemprop="name">
            <a href="https://blog.xiongtianci.com" itemprop="url" rel="author">木浅</a>
            </h3>
          </div>
        </div>
        <hr>
        <p><i class="iconfont icon-write"></i>YOLO</p>
      </section>
    </main><!-- #main -->
  </div><!-- #primary -->
</div>


    </div>    
    <div class="ins-search">
    <div class="ins-search-mask"></div>
    <div class="ins-search-container">
        <div class="ins-input-wrapper">
            <input type="text" class="ins-search-input" placeholder="Type something..."/>
            <span class="ins-close ins-selectable"><i class="fa fa-times-circle"></i></span>
        </div>
        <div class="ins-section-wrapper">
            <div class="ins-section-container"></div>
        </div>
    </div>
</div>
<script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: 'Posts',
            // PAGES: 'Pages',
            CATEGORIES: 'Categories',
            TAGS: 'Tags',
        },
        ROOT_URL: '/',
        CONTENT_URL: '/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>
    <!-- <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      &copy; 2025 天赐<br>
      powered_by <a href="http://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer> -->
<footer id="colophon" class="site-footer" role="contentinfo">
	<div class="site-info">
		<div class="footertext">
			<div class="img-preload">
				<img src="https://cdn.jsdelivr.net/gh/tiancixiong/cdn@1.0/img/other/wordpress-rotating-ball-o.svg">
				<img src="https://cdn.jsdelivr.net/gh/tiancixiong/cdn@1.0/img/other/disqus-preloader.svg">
			</div>
			<p class="foo-logo"
				style="background-image: url('https://cdn.jsdelivr.net/gh/tiancixiong/cdn@sakura-theme/img/custom/sakura.svg');">
			</p>
			<div
				style="background-image:linear-gradient(90deg,#6dba82 0,#07b39b 15%,#1098ad 30%,#5073b8 44%,#a166ab 58%,#ef4e7b 72%,#f37055 86%,#f79533 100%);background-size:cover;-webkit-background-clip:text;-webkit-text-fill-color:transparent;user-select:none;margin-top:0.7em;">
				<i>Tip: 本站电脑访问体验更佳耶&nbsp;<i class="fa fa-angellist" style="display:inline"></i></i>
			</div>
			<!-- color: #666666; -->
			<div style="color: #b9b9b9;">&copy;
				2018-2025&nbsp;天赐&nbsp;
			</div>
		</div>
		<!-- 访客统计 -->
		<!--<div id="busuanzi_container"></div>-->
		<!-- 已运行的时间-容器 -->
		<div id="days"></div>
		<div class="footer-device">
			<p id="footer-sponsor">
				<!-- <a href="https://pages.github.com/" target="_blank" alt="GitHub Pages" rel="nofollow"><img
						src="https://cdn.jsdelivr.net/gh/tiancixiong/cdn@1.0/img/logo/GitHub.svg" alt="GitHub Pages"
						style="height: 2em; max-height: 2em;" title=""></a>&nbsp;&nbsp;&nbsp; -->
				<!-- <a href="https://coding.net/pages" target="_blank" alt="Coding Pages" rel="nofollow"><img
						src="https://cdn.jsdelivr.net/gh/tiancixiong/cdn@1.0/img/logo/Coding.png" alt="Coding Pages"
						style="height: 1.3em; max-height: 1.3em;padding-bottom: 0px;margin-bottom: 0.35em;"
						title=""></a>&nbsp;&nbsp;&nbsp; -->
				<a href="https://www.jsdelivr.com/" target="_blank" alt="Free CDN" rel="nofollow"><img
						src="https://cdn.jsdelivr.net/gh/tiancixiong/cdn@sakura-theme/img/logo/JsDelivr_Logo.svg" alt="jsDelivr"
						style="height: 2em; max-height: 2em;padding-bottom: 0px;"></a>&nbsp;&nbsp;&nbsp;<a
					href="https://www.google.com/intl/ja/analytics/" target="_blank" alt="Analytics solution"
					rel="nofollow"><img src="https://cdn.jsdelivr.net/gh/tiancixiong/cdn@sakura-theme/img/logo/Google.svg"
						alt="Google Analytics" style="height: 1.7em; max-height: 1.7em;padding-bottom: 0px;"></a>
			</p>
		</div>
	</div>
	<!-- .site-info -->
</footer>

<!-- <script src="/js/tocbot.js"></script> -->
<script type="text/javascript" src="https://cdn.jsdelivr.net/gh/tiancixiong/cdn@sakura-theme/js/lib.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/tiancixiong/cdn@sakura-theme/js/vendor/clipboard.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/gh/tiancixiong/cdn@sakura-theme/js/InsightSearch.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/gh/tiancixiong/cdn@sakura-theme/js/jquery.fancybox.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/gh/tiancixiong/cdn@sakura-theme/js/zoom.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/gh/tiancixiong/cdn@sakura-theme/js/sakura-app.js"></script>
<!--浏览器搞笑标题-->
<!--<script type="text/javascript" src="https://cdn.jsdelivr.net/gh/tiancixiong/cdn@sakura-theme/js/title_change.js"></script>-->
<script type="text/javascript" src="https://cdn.jsdelivr.net/gh/tiancixiong/cdn@sakura-theme/js/volantis.min.js"></script>
<!-- Valine -->
<!--<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>-->
<script src='//unpkg.com/valine/dist/Valine.min.js'></script>
<!--<script src='//unpkg.com/valine@1.3.4/dist/Valine.min.js'></script>-->
<!--<script src="//unpkg.com/valine@1.3.7/dist/Valine.min.js"></script>-->
<!-- 不蒜子 网页计数器 -->
<script src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.4.2/tocbot.min.js"></script> -->
<script type="text/javascript">
	/* <![CDATA[ */
	if (/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
		var Poi = {
			"pjax": "1",
			"movies": {
				"url": "https://cdn.jsdelivr.net/gh/tiancixiong/cdn@v3.0",
				"name": "/video/Unbroken.mp4",
				"live": "close"
			},
			"windowheight": "fixed",
			"codelamp": "close",
			"ajaxurl": "",
			"order": "asc",
			"formpostion": "bottom"
		};
	} else {
		var Poi = {
			"pjax": "1",
			"movies": {
				"url": "https://cdn.jsdelivr.net/gh/tiancixiong/cdn@v3.0",
				"name": "/video/Unbroken.mp4",
				"live": "open"
			},
			"windowheight": "auto",
			"codelamp": "close",
			"ajaxurl": "",
			"order": "asc",
			"formpostion": "bottom"
		};
	}
		/* ]]> */
</script>
<script>
	$(document).ready(function () {
		if ($(".toc").length > 0 && document.body.clientWidth > 1200) {
			if ($(".pattern-center").length > 0) { //有图的情况
				tocbot.init({
					// Where to render the table of contents.
					tocSelector: '.toc', // 放置目录的容器
					// Where to grab the headings to build the table of contents.
					contentSelector: '.entry-content', // 正文内容所在
					// Which headings to grab inside of the contentSelector element.
					scrollSmooth: true,
					headingSelector: 'h1, h2, h3, h4, h5', // 需要索引的标题级别
					headingsOffset: -400,
					scrollSmoothOffset: -85
				});
			} else {
				tocbot.init({
					// Where to render the table of contents.
					tocSelector: '.toc', // 放置目录的容器
					// Where to grab the headings to build the table of contents.
					contentSelector: '.entry-content', // 正文内容所在
					// Which headings to grab inside of the contentSelector element.
					scrollSmooth: true,
					headingSelector: 'h1, h2, h3, h4, h5', // 需要索引的标题级别
					headingsOffset: -85,
					scrollSmoothOffset: -85
				});
			}
			var offsetTop = $('.toc').offset().top - 95;
			window.onscroll = function () {
				var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
				if (scrollTop >= offsetTop) {
					$('.toc').addClass('toc-fixed');
				} else {
					$('.toc').removeClass('toc-fixed');
				}
			}
		}
	});
</script>
<!-- 已运行的时间-js -->
<script>
	function show_date_time() {
		window.setTimeout("show_date_time()", 1000);
		// 获得建站时间
		var time = "28/11/2018 15:36:06";
		time = time.replace(/\//g, ':').replace(' ', ':');
		time = time.split(':');
		BirthDay = new Date(time[2], (time[1] - 1), time[0], time[3], time[4], time[5]);

		today = new Date();
		timeold = (today.getTime() - BirthDay.getTime());
		sectimeold = timeold / 1000
		secondsold = Math.floor(sectimeold);
		msPerDay = 24 * 60 * 60 * 1000
		msPerYear = 365 * 24 * 60 * 60 * 1000
		e_yearsold = timeold / msPerYear
		yearsold = Math.floor(e_yearsold);
		//e_daysold = timeold / msPerDay
		e_daysold = timeold/msPerDay - yearsold*365;
		daysold = Math.floor(e_daysold);
		e_hrsold = (e_daysold - daysold) * 24;
		hrsold = setzero(Math.floor(e_hrsold));
		e_minsold = (e_hrsold - hrsold) * 60;
		minsold = setzero(Math.floor((e_hrsold - hrsold) * 60));
		seconds = setzero(Math.floor((e_minsold - minsold) * 60));
		document.getElementById('days').innerHTML = "已在风雨中运行 " + yearsold + " 年 " + daysold + " 天 " + hrsold + " 小时 " + minsold + " 分 " + seconds + " 秒";
	}

	function setzero(i) {
		if (i < 10) {
			i = "0" + i
		};
		return i;
	}
	show_date_time();
</script>
<!-- 访客统计-js -->
<!--<script>
		if(true){
			document.getElementById('busuanzi_container').innerHTML="<span id=\"busuanzi_container_site_pv\">本站总访问量 <span id=\"busuanzi_value_site_pv\"></span> 次</span><span class=\"post-meta-divider\"> | </span><span id=\"busuanzi_container_site_uv\">本站访客数 <span id=\"busuanzi_value_site_uv\"></span> 人</span>";
		}else{
			document.getElementById('busuanzi_container').hidden;
		}
	</script>-->
<!-- 百度统计自动推送 -->
<!--<script>
	(function(){
		var bp = document.createElement('script');
		var curProtocol = window.location.protocol.split(':')[0];
		if (curProtocol === 'https') {
			bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
		}
		else {
			bp.src = 'http://push.zhanzhang.baidu.com/push.js';
		}
		var scriptList = document.getElementsByTagName("script");
		var s = scriptList[0];
		s.parentNode.insertBefore(bp, s);
	})();
	</script>
	-->
    <div class="openNav no-select" style="height: 50px;">
      <div class="iconflat no-select" style="width: 50px; height: 50px;">
        <div class="icon"></div>
      </div>
      <div class="site-branding search-form-submit">
        <i class="iconfont js-toggle-search iconsearch icon-search"></i>
      </div>
    </div>
  </section>
  
  <!-- 实现换肤功能 -->
  <div class="skin-menu no-select" id="mainskin"  style="position: fixed">
    <div class="theme-controls row-container">
        <ul class="menu-list">
            <li id="white-bg"><i class="fa fa-television" aria-hidden="true"></i></li>
            <li id="sakura-bg"> <i class="iconfont icon-sakura"></i></li>
            <li id="gribs-bg"> <i class="fa fa-slack" aria-hidden="true"></i></li>
            <li id="KAdots-bg"> <i class="iconfont icon-dots"></i></li>
            <li id="totem-bg"> <i class="fa fa-optin-monster" aria-hidden="true"></i></li>
            <li id="pixiv-bg"> <i class="iconfont icon-pixiv"></i></li>
            <li id="bing-bg"> <i class="iconfont icon-bing"></i></li>
            <li id="dark-bg"> <i class="fa fa-moon-o" aria-hidden="true"></i></li>
        </ul>
    </div>
</div>

<canvas id="night-mode-cover"></canvas>
<style>
#mainskin{
    position: fixed;
}
</style> 
  <div class="changeSkin-gear no-select">
    <div class="keys" id="setbtn"> <span id="open-skinMenu"> 切换主题 | SCHEME TOOL &nbsp;
	<i class="iconfont icon-gear inline-block rotating"></i> </span></div>
</div>
  
  <div id="mo-nav" class="">
  <div class="m-avatar">
    <img src="https://fastly.jsdelivr.net/gh/tiancixiong/cdn@v1.0/img/custom/avatar.jpg">
  </div>
  <p style="text-align: center; color: #333; font-weight: 900; font-family: 'Ubuntu', sans-serif; letter-spacing: 1.5px">天赐の小站</p>
  <p style="text-align: center; word-spacing: 20px;">
    
  </p>
  <ul id="menu-new-1" class="menu">
    
      <li>
        <a href="/">
          <span class="faa-parent animated-hover">
            <i class="fa  fa-fort-awesome faa-horizontal" aria-hidden="true"></i>
            首页
          </span>
        </a>
        
      </li>
    
      <li>
        <a href="/archives">
          <span class="faa-parent animated-hover">
            <i class="fa  fa-terminal faa-vertical" aria-hidden="true"></i>
            极客
          </span>
        </a>
        
          <ul class="sub-menu">
            
              <li>
                <a href="/categories/技术/">
                  <i class="fa fa-code" aria-hidden="true"></i>
                  技术
                </a>
              </li>
            
              <li>
                <a href="/categories/Linux/">
                  <i class="fa fa-linux" aria-hidden="true"></i>
                  Linux
                </a>
              </li>
            
          </ul>
        
      </li>
    
      <li>
        <a href="/archives">
          <span class="faa-parent animated-hover">
            <i class="fa  fa-slack faa-spin" aria-hidden="true"></i>
            爱好
          </span>
        </a>
        
          <ul class="sub-menu">
            
              <li>
                <a href="/categories/电影/">
                  <i class="fa fa-film" aria-hidden="true"></i>
                  电影
                </a>
              </li>
            
              <li>
                <a href="/categories/日语/">
                  <i class="fa fa-language" aria-hidden="true"></i>
                  日语
                </a>
              </li>
            
          </ul>
        
      </li>
    
      <li>
        <a href="/archives">
          <span class="faa-parent animated-hover">
            <i class="fa  fa-archive faa-ring" aria-hidden="true"></i>
            归档
          </span>
        </a>
        
          <ul class="sub-menu">
            
              <li>
                <a href="/categories/生活/">
                  <i class="fa fa-file-text-o" aria-hidden="true"></i>
                  生活
                </a>
              </li>
            
              <li>
                <a href="/categories/随想/">
                  <i class="fa fa-commenting-o" aria-hidden="true"></i>
                  随想
                </a>
              </li>
            
              <li>
                <a href="/categories/资源/">
                  <i class="fa fa-cloud-download" aria-hidden="true"></i>
                  资源
                </a>
              </li>
            
              <li>
                <a href="/categories/转载/">
                  <i class="fa fa-book" aria-hidden="true"></i>
                  转载
                </a>
              </li>
            
          </ul>
        
      </li>
    
      <li>
        <a href="/comment/">
          <span class="faa-parent animated-hover">
            <i class="fa  fa-pencil-square-o faa-tada" aria-hidden="true"></i>
            留言板
          </span>
        </a>
        
      </li>
    
      <li>
        <a href="/links/">
          <span class="faa-parent animated-hover">
            <i class="fa  fa-link faa-shake" aria-hidden="true"></i>
            友人帐
          </span>
        </a>
        
      </li>
    
      <li>
        <a href="/donate/">
          <span class="faa-parent animated-hover">
            <i class="fa  fa-heart faa-burst" aria-hidden="true"></i>
            赞赏
          </span>
        </a>
        
      </li>
    
      <li>
        <a href="/">
          <span class="faa-parent animated-hover">
            <i class="fa  fa-leaf faa-falling" aria-hidden="true"></i>
            关于
          </span>
        </a>
        
          <ul class="sub-menu">
            
              <li>
                <a href="/about/">
                  <i class="fa fa-meetup" aria-hidden="true"></i>
                  我？
                </a>
              </li>
            
              <li>
                <a href="/theme-sakura/">
                  <i class="fa iconfont icon-sakura" aria-hidden="true"></i>
                  主题
                </a>
              </li>
            
          </ul>
        
      </li>
    
      <li>
        <a href="/atom.xml">
          <span class="faa-parent animated-hover">
            <i class="fa  fa-rss faa-passing" aria-hidden="true"></i>
            RSS
          </span>
        </a>
        
      </li>
    
  </ul>
  <p style="text-align: center; font-size: 13px; color: #b9b9b9;">&copy 2019 hexo-sakura</p>
</div>
<button onclick="topFunction()" class="mobile-cd-top" id="moblieGoTop" title="Go to top" style="display: none;"><i class="fa fa-chevron-up" aria-hidden="true"></i></button>
  <!--<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.css">-->
<!--<script src="https://cdn.jsdelivr.net/npm/aplayer@1.10.1/dist/APlayer.min.js"></script>-->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/tiancixiong/cdn@sakura-theme/css/aplayer/APlayer.min.css">
<script src="https://cdn.jsdelivr.net/gh/tiancixiong/cdn@sakura-theme/js/aplayer/APlayer.min.js"></script>

<style>
  .aplayer .aplayer-lrc {
    height: 35px;
  }
  .aplayer .aplayer-lrc p{
    font-size: 16px;
    font-weight: 700;
    line-height: 18px !important;
  }
  .aplayer .aplayer-lrc p.aplayer-lrc-current{
    color: #FF1493;
  }
  /*.aplayer.aplayer-narrow .aplayer-body{
    left: -66px !important;
  }*/
  .aplayer.aplayer-fixed .aplayer-lrc {
    display: none;
  }
  .aplayer .aplayer-lrc.aplayer-lrc-hide {
      display:none !important;
  }
  .aplayer.aplayer-fixed .lrc-show {
    display: block;
    background: rgba(255, 255, 255, 0.8);
  }
</style>
<div class="aplayer"

    data-id="7040682880"

    data-server="tencent"

    data-type="playlist"

    data-fixed="true"

    data-autoplay="false"

    data-loop="all"

    data-order="random"

    data-preload="auto"

    data-volume="0.5"

    data-mutex="true"

    data-listFolded="false"

</div>
<!-- Meting 一个支持各种音乐平台(腾讯、网易...)的音乐 API 框架 -->
<!--<script src="https://cdn.jsdelivr.net/npm/meting@2.0.1/dist/Meting.min.js"></script>-->
<script src="https://cdn.jsdelivr.net/gh/tiancixiong/cdn@sakura-theme/js/aplayer/Meting.min.js"></script>
<script>
  $(function(){
    $('body').on('click', '.aplayer', function(){
      if($('.aplayer-button').hasClass('aplayer-play')) {
        $('.aplayer-lrc').removeClass('lrc-show');
      } else {
        $('.aplayer-lrc').addClass('lrc-show');
      }
    })
  });
</script>
</body>
</html>